package middleware

import (
	"fresh-shop-gin/model/common"
	"fresh-shop-gin/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

const (
	contextKeyClaims = "jwtClaims"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// jwtClaims := utils.JWTAuth{}
		// 从请求头中获取token
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			common.Error(c, http.StatusUnauthorized, common.CodeUnauthorized, "未提供token")
			c.Abort()
			return
		}

		// 验证token
		claims, err := utils.ValidateToken(tokenString)
		if err != nil {
			common.Error(c, http.StatusUnauthorized, common.CodeUnauthorized, "token无效")
			c.Abort()
			return
		}

		// 存储用户信息到上下文
		c.Set(contextKeyClaims, claims)
		c.Next()
	}
}

// 从上下文获取用户信息
func GetUserInfo(c *gin.Context) *utils.CustomClaims {
	claims, exists := c.Get(contextKeyClaims)
	if !exists {
		return nil
	}
	return claims.(*utils.CustomClaims)
}
